'''
Created on 2011-4-30

@author: mark
'''
import web
import datetime
import time
import config
from model import user

def login(func):
    def wrapper(*p):
        current_user = web.ctx.session['current_user']
        if current_user:
            return func(*p)
        else:
            web.seeother("/login")
    return wrapper 

def setcookie(user, remember=False):
    text = cookie(user)
    expires = (remember and config.cookie_expire) or ''
    web.setcookie("ixuan_session", text, expires=expires)
    
def cookie(user):
    t = datetime.datetime(*time.gmtime()[:6]).isoformat()
    return '%s/%s/%s' % (user.uid, user.passwd, str(t))

def setLogoutCookie():
    web.setcookie("ixuan_session", "")

def validatecookie(cookie):
    cookie = web.cookies()['ixuan_session']
    try:
        uid, passwd, t = cookie.split("/")
    except Exception,e:
        return None
    _user = user.getuserbyid(uid)
    if _user:
        if passwd == _user['passwd']:
            return _user
    else:
        return None
    
def logoutCookie():
    web.setcookie("ixuan_session", "")
    
def checkCaptcha(captcha):
    _captcha = web.ctx.session['captcha']
    return _captcha == captcha

def updateSessionUser(uid):
    updateuser = user.getuserbyid(uid)
    web.ctx.session['current_user'] = updateuser